work_dir=$(pwd)
# jar包名称
jar_name=`ls *.jar | head -n 1`
file_name=`echo $jar_name | sed 's/.jar//'`
service_name=$file_name

function usage(){
    echo "Dspring.profiles.active Usage: gen.sh [dev|test|prod|...]"
    exit 1
}

function gen_app(){
    # 替换工作目录
    sed -i "s|/opt/project/app|$work_dir|g" app.sh

    # 替换运行jar包
    sed -i "s|app_name|$file_name|g" app.sh

    # 替换环境变量
    env=$1
    sed -i "s|env|$env|g" app.sh

    chmod 777 app.sh
}

function gen_service(){
    echo -e "
[Unit]
Description=SpringBoot Application $jar_name
Documentation=https://spring.io/
After=network-online.target firewalld.service
Wants=network-online.target

[Service]
Type=forking
User=root
WorkingDirectory=$work_dir
ExecStart=/bin/sh $work_dir/app.sh start
ExecReload=/bin/sh $work_dir/app.sh restart
ExecStop=/bin/sh $work_dir/app.sh stop

[Install]
WantedBy=multi-user.target
    " > /lib/systemd/system/$service_name.service
    chmod 644 /lib/systemd/system/$service_name.service
    systemctl daemon-reload
    echo "genarate service success, path:/lib/systemd/system/$service_name.service"
}

if [ -z "$1" ]; then
    usage
else
    gen_app $1
    gen_service
fi